package com.tamakloe.guestbook;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(GuestbookServlet.class.getName());
    private static final String VIEW = "guestbook.jsp";
    private static final String ATTRIBUTE_GREET = "greetings";	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Greeting.class.getName()
				+ " order by date desc ";
		List<Greeting> greetings = (List<Greeting>) pm.newQuery(query).execute();
		req.setAttribute(ATTRIBUTE_GREET, greetings);
		
     	// Show view.
     	try {
			req.getRequestDispatcher(VIEW).forward(req, resp);
		} catch (ServletException e) {
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			log.severe(sw.toString());
		} catch (RuntimeException e){
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			log.severe(sw.toString());	
		}
		pm.close();
	}
}
